<template>
	<view class="addProject">
		<uni-forms ref="form" :modelValue="formData">
			<uni-forms-item label="发布人" required>
				<uni-easyinput isLoading placeholder="请输入发布人" v-model="formData.createName" />
			</uni-forms-item>
			<uni-forms-item label="项目名称" required>
				<uni-easyinput placeholder="请输入项目名称" v-model="formData.projectName" />
			</uni-forms-item>
			<uni-forms-item label="项目时间" required>
				<uni-datetime-picker type="daterange" v-model="itemrange" @change="itemchange" />
			</uni-forms-item>
			<uni-forms-item label="项目介绍" required>
				<uni-easyinput type="textarea" placeholder="请输入项目介绍" v-model="formData.briefly" />
			</uni-forms-item>
			<uni-forms-item label="项目类型" required>
				<uni-data-picker class="w100" placeholder="请选择项目类型" popup-title="请选择类型" v-model="formData.content"
					@change="onchange()" :localdata="dataTree">
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item label="项目范围" required>

				<view class="tagsList">
					<template v-for="(item,index) in formData.tags">
						<tag :name='item' :data-index="index" @click.native="delt(index)"></tag>
					</template>

				</view>
				<view class="jiahao" @click="tianjia">
					<image src="/static/jiahao.png" mode=""></image>
				</view>
			</uni-forms-item>
			<uni-forms-item label="项目投资金额" required>
				<uni-easyinput placeholder="请输入项目投资金额(元)" v-model="formData.reward" />
			</uni-forms-item>
			<uni-forms-item label="发布人联系方式" required>
				<uni-easyinput placeholder="请输入发布人联系方式" v-model="formData.connectPublisher" />
			</uni-forms-item>
			<uni-forms-item label="项目来源" required>
				<uni-easyinput placeholder="请输入项目来源" v-model="formData.place" />
			</uni-forms-item>
			<uni-forms-item label="图片上传">
				<view class="example-body">
					<uni-file-picker v-if="!isUploadSomeError" v-model="imageValue" fileMediatype="image" mode="grid"
						@select="select" @fail="fail" limit="9" title="最多选择9张图片" delIcon="false">
					</uni-file-picker>
					<view class="fileUpload" v-else>
						<view class="color-red">以下图片上传失败，请点击重传</view>
						<view class="fileUploadList">
							<template v-for="(item,index) in fileerrorList">
								<view :key="item.path" class="errUploadImage" @click.native="reloadUpload(index)">
									<image :src="item.path"></image>
								</view>
							</template>
						</view>

					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item>
				<button type="primary" :disabled="isLoading" @click="submit" class="w100"
					:loading="isLoading">提交</button>
			</uni-forms-item>

		</uni-forms>
		<modal v-if="areaShow" @cancel="cancelAdd" @confirm="confirmAdd" title="新增标签" confirm-text="保存"
			cancel-text="取消">
			<input type="text" v-model="areaTxt" placeholder="填写你想加的标签" class="intxt" maxlength="10" />
		</modal>
		<modal v-if="del" @cancel="canceldel" @confirm="confirmdel" title="是否删除此标签？" confirm-text="删除" cancel-text="取消">
		</modal>

	</view>
</template>

<script>
	import tag from "@/components/tag/index.vue";
	export default {
		components: {
			tag
		},
		data() {
			return {
				errImageLoading: false,
				isUploadSomeError: false,
				fileerrorList: [],
				projectId: '',
				del: false,
				index: '',
				areaShow: false,
				areaTxt: '',
				isLoading: false,
				itemrange: ['', ''],
				formData: {
					tags: [],
					content: '', //项目类型，内容
					briefly: '', //简介/项目介绍
					connectPublisher: '', //发布者联系方式
					createName: '', //发布人姓名
					endTime: '', //报名结束时间
					place: '', //地点/项目来源
					projectEndTime: '', //结束时间
					projectName: '', //项目标题(名字)
					projectStartTime: '', //开始时间
					reward: '', //奖励/项目投资金额
					startTime: '', //报名开始时间
					type: '0' //类型:比赛1项目0
				},
				imageValue: [],
				dataTree: [{
						instituteId: 1,
						text: "服务",
						value: "服务",
					},
					{
						instituteId: 2,
						text: "管理",
						value: "管理",

					},
					{
						instituteId: 3,
						text: "技术",
						value: "技术",
					},
					{
						instituteId: 4,
						text: "市场",
						value: "市场",
					}
				],
				pathValue: []
			};
		},
		mounted() {
			this.$eventBus.$emit('sendItemEditMsg')
		},
		methods: {
			handleUploadImage() {
				//遍历数组，查看错误位置
				this.isUploadSomeError = true
				const list = this.pathValue
				console.log(list, 296);
				const errIndexList = list.map(item => {
					console.log(item.done, 298);
					if (!item.done) {
						return {
							done: false,
							path: item.path
						}
					}

				})
				console.log(errIndexList, 'errIndexList');
				this.fileerrorList = errIndexList
				uni.hideLoading();
				uni.showToast({
					title: '发布成功，但存在图片上传失败',
					duration: 2000,
					icon: 'none'
				})

			},
			reloadUpload(index) {

				if (this.errImageLoading) return
				console.log(index);
				this.errImageLoading = true
				const path = this.fileerrorList[index].path
				console.log(path, 135);
				uni.uploadFile({
					url: "https://513309q9o0.zicp.fun" + this.$api.uploadFile, //仅为示例，非真实的接口地址
					filePath: path,
					name: "file",
					header: this.$aplsFormDataheader,
					formData: {
						projectId: this.projectId,
					},
					success: (res) => {
						this.errImageLoading = false
						const result = JSON.parse(res.data);
						console.log(result, 146);
						if (result.code != 200) {
							this.$errMessageToast(result.msg)
							return
						}
						this.$nextTick(() => {
							this.fileerrorList.slice(index, 1)

						})

					},
					fail: (eee) => {
						this.errImageLoading = false
						this.$errMessageToast('上传失败，请查看')
					},
				});
			},
			returnimageUpload(path, i) {
				console.log(path, i);
				console.log(this.projectId);
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: "https://513309q9o0.zicp.fun" + this.$api.uploadFile, //仅为示例，非真实的接口地址
						filePath: path,
						name: "file",
						header: this.$aplsFormDataheader,
						formData: {
							projectId: this.projectId,
						},
						success: (res) => {
							const result = JSON.parse(res.data);


							if (result.code != 200) {

								this.pathValue[i].done = false


								reject('错误')

								return
							}
							const imgUrl = result.data
							if (!imgUrl) {
								reject('')
								return
							}

							resolve(imgUrl)
						},
						fail: (eee) => {
							reject('上传失败')
							this.$errMessageToast('上传失败，请查看')
						},
					});
				})
			},
			confirmdel() {
				this.formData.tags.splice(this.index, 1)
				this.del = false
			},
			fail(e) {
				this.$errMessageToast(e.errMsg || e);
			},
			select(e) {
				console.log("上传成功");
				const tempFiles = e.tempFiles
				for (let i = 0; i < tempFiles.length; i++) {
					this.pathValue.push({
						path: e.tempFiles[i].path,
						done: true
					});
				}

			},
			tianjia() {
				this.areaShow = true
			},
			confirmAdd(e) {
				console.log(this.areaTxt);
				if (this.areaTxt.length == 0) {

					this.$errMessageToast('不能为空')
					return
				}
				if (this.formData.tags.indexOf(this.areaTxt) != -1) {
					this.$errMessageToast('有重复的标签')
					return
				}

				if (this.formData.tags.length == 6) {
					this.$errMessageToast('标签最多6个')
					return
				}
				this.formData.tags.push(this.areaTxt)
				this.areaTxt = ''
				this.areaShow = false
			},
			cancelAdd() {

				this.areaShow = false
				this.areaTxt = ''
			},
			canceldel() {
				this.del = false
			},
			onchange(e) {

				this.formData.content = e.detail.value[0].text
			},
			delt(index) {
				this.del = true
				this.index = index
			},

			itemchange(e) {
				this.formData.projectStartTime = e[0]
				this.formData.projectEndTime = e[1]
				this.formData.startTime = e[0]
				this.formData.endTime = e[1]
			},
			timestampToTime(timestamp) {

				var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = date.getDate() + ' ';
				return Y + M + D;
			},
			vaildType() {

				if (this.formData.createName == '' || this.formData.createName == undefined) {

					throw new Error('请填写发布人')
				}
				if (this.formData.projectName == '' || this.formData.projectName == undefined) {

					throw new Error('请填写项目名称')
				}
				if (this.formData.briefly == '' || this.formData.briefly == undefined) {

					throw new Error('请填写项目介绍')
				}

				if (this.formData.projectStartTime == '' || this.formData.projectStartTime == undefined) {
					throw new Error('请选择项目开始时间')
				}
				if (this.formData.projectEndTime == '' || this.formData.projectEndTime == undefined) {
					throw new Error('请选择项目结束时间')
				}
				if (
					new Date(this.formData.projectStartTime).getTime() >
					new Date(this.formData.projectEndTime).getTime()
				) {
					throw new Error("项目开始日期不能大于结束日期");
				}
				if (
					new Date(this.formData.projectStartTime).getTime() ==
					new Date().getTime()
				) {
					throw new Error("项目开始日期不能是今天");
				}

				if (
					new Date(this.formData.projectStartTime).getTime() ==
					new Date(this.formData.projectEndTime).getTime()
				) {
					throw new Error("项目开始日期不可以和结束日期同一天");
				}
				if (this.formData.content == '' || this.formData.content == undefined) {
					throw new Error('请选择项目类型')
				}
				if (this.formData.tags.length == 0) {
					throw new Error('请添加至少一个标签')
				}
				if (this.formData.reward == '' || this.formData.reward == undefined) {
					throw new Error('请填写项目投资金额')
				}
				if (this.formData.connectPublisher == '' || this.formData.connectPublisher == undefined) {
					throw new Error('请填写发布人联系方式')
				}

				if (!(/^1[3456789]\d{9}$/.test(this.formData.connectPublisher))) {

					throw new Error('发布人联系方式有误，请重填')
				}
				if (this.formData.place == '' || this.formData.place == undefined) {
					throw new Error('请填写项目来源')
				}

				return true
			},
			async submit() {
				console.log('11')
				try {
					if (this.vaildType()) {
						const data = {
							...this.formData
						}

						this.isLoading = true
						const result = await this.$mjcrequest.request({
							url: this.$api.addProject,
							data: JSON.stringify(data),
							header: this.$aplsjsonheader,
							isToast: true
						})
						if (this.pathValue.length == 0) {
							this.$setTimeoutback()
							return
						}
						uni.showLoading({
							title: '正在上传图片'
						})
						this.projectId = result.project.projectId
						console.log(this.projectId, 'this.projectId');
						const promiseList = []
						const files = this.pathValue



						for (let i = 0; i < files.length; i++) {

							const path = files[i].path
							const item = this.returnimageUpload(path, i)
							console.log(item, 936);
							promiseList.push(item)
						}
						console.log(promiseList, 397);

						Promise.allSettled(promiseList).then(res => {
							const isErrorSome = res.some(item => {
								return item.status != 'fulfilled'
							})
							console.log(isErrorSome, 'isErrorSome');
							uni.hideLoading();
							if (isErrorSome) {
								//存在失败
								this.handleUploadImage()
								return
							}

							uni.showToast({
								title: '所有信息上传成功，等待审核',
								icon: 'none',
								duration: 1100
							})
							this.$setTimeoutback()
						})

						//文件遍历上传

					}
				} catch (errMessage) {

					this.isLoading = false
					//TODO handle the exception
					this.$errMessageToast(errMessage.message || errMessage)
				}
			}
		},
		created() {
			this.$eventBus.$on('editItemMsg', (editItem) => {
				console.log(editItem, 'edit item 555')
				this.formData = editItem
				this.itemrange[0] = editItem.projectStartTime
				this.itemrange[1] = editItem.projectEndTime
			})
		},
		beforeDestroy() {
			console.log('beforeDestroy')
			this.$eventBus.$off('editItemMsg')
		}
	}
</script>

<style lang="scss">
	.addProject {
		height: auto;
		padding: 10rpx 20rpx 15rpx 20rpx;
		background-color: #fff;

		.tagsList {
			max-width: calc(100% - 25rpx) !important;
			width: auto;
		}

		.fileUpload {
			display: flex;
			flex-direction: column;
			flex-wrap: wrap;

			& .fileUploadList {
				display: flex;
				flex-wrap: wrap;
			}
		}

		.jiahao {
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			overflow: hidden;

			& image {
				width: 100%;
				height: 100%;
			}
		}

		.uni-forms-item__content {
			display: flex;
			align-items: center;
		}

		.w100 {
			width: 100%;
		}
	}
</style>
